package com.gxa.controller;

//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gxa.domain.entity.PromotionProduct;
import com.gxa.domain.vo.PromotionProductVO;
import com.gxa.service.PromotionProductService;
import com.gxa.service.ProductService;
import com.gxa.domain.entity.Product;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.dao.DataIntegrityViolationException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

//import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;

@RestController
@RequestMapping("/api/promotion-products")
@Tag(name = "活动管理", description = "活动信息管理相关接口")
@CrossOrigin(origins = "*")
public class PromotionProductController {
    // 注入PromotionProductService
    @Autowired
    private PromotionProductService promotionProductService;
    // 注入ProductService
    @Autowired
    private ProductService productService;

    // 获取所有促销商品（带名称），支持条形码搜索
    @GetMapping
    public List<PromotionProductVO> list(@RequestParam(value = "barcode", required = false) String barcode) {
        if (barcode != null && !barcode.trim().isEmpty()) {
            // 条形码搜索，查所有相关活动，直接返回VO列表
            return promotionProductService.getPromotionProductByBarcode(barcode);
        } else {
            return promotionProductService.getPromotionProduct();
        }
    }

    // 根据detailId获取促销商品
    @GetMapping("/{detailId}")
    public PromotionProduct get(@PathVariable Integer detailId) {
        return promotionProductService.getById(detailId);
    }

    // 添加促销商品
    @PostMapping
    public Map<String, Object> add(@RequestBody PromotionProduct promotionProduct) {
        // 关键：将空字符串转为null，避免唯一索引冲突
        if (promotionProduct.getBarcode() != null && promotionProduct.getBarcode().trim().isEmpty()) {
            promotionProduct.setBarcode(null);
        }
        // 自动计算promotion_price
        if (promotionProduct.getProductSerialNo() != null && promotionProduct.getDiscount() != null) {
            try {
                Integer serialNo = Integer.valueOf(promotionProduct.getProductSerialNo());
                Product product = productService.findProductById(serialNo);
                if (product != null && product.getSellingPrice() != null) {
                    BigDecimal promotionPrice = product.getSellingPrice().multiply(promotionProduct.getDiscount());
                    promotionProduct.setPromotionPrice(promotionPrice);
                }
            } catch (Exception e) {
                // 异常处理，保留原有逻辑
                System.err.println("自动计算promotion_price失败: " + e.getMessage());
            }
        }
        Map<String, Object> result = new HashMap<>();
        try {
            // 调用PromotionProductService的save方法保存促销商品
            boolean saveResult = promotionProductService.save(promotionProduct);
            System.out.println("保存promotion_product结果：" + saveResult);
            result.put("success", saveResult);
            if (saveResult) {
                result.put("msg", "新增成功");
            } else {
                result.put("msg", "新增失败，数据不合法或外键约束失败");
            }
        } catch (DataIntegrityViolationException e) {
            Throwable cause = e.getCause();
            // 判断异常原因是否包含外键约束失败
            if (cause != null && cause.getMessage() != null && cause.getMessage().contains("a foreign key constraint fails")) {
                result.put("success", false);
                result.put("msg", "商品编号或活动ID不存在！");
                return result;
            }
            throw e;
        }
        return result;
    }

    // 修改促销商品
    @PutMapping
    public Map<String, Object> update(@RequestBody PromotionProduct promotionProduct) {
        // 自动计算promotion_price
        if (promotionProduct.getProductSerialNo() != null && promotionProduct.getDiscount() != null) {
            try {
                Integer serialNo = Integer.valueOf(promotionProduct.getProductSerialNo());
                Product product = productService.findProductById(serialNo);
                if (product != null && product.getSellingPrice() != null) {
                    BigDecimal promotionPrice = product.getSellingPrice().multiply(promotionProduct.getDiscount());
                    promotionProduct.setPromotionPrice(promotionPrice);
                }
            } catch (Exception e) {
                // 异常处理，保留原有逻辑
                System.err.println("自动计算promotion_price失败: " + e.getMessage());
            }
        }
        Map<String, Object> result = new HashMap<>();
        try {
            // 调用PromotionProductService的updateById方法修改促销商品
            boolean updateResult = promotionProductService.updateById(promotionProduct);
            result.put("success", updateResult);
            if (updateResult) {
                result.put("msg", "修改成功");
            } else {
                result.put("msg", "修改失败，可能是数据不合法或外键约束失败");
            }
        } catch (DataIntegrityViolationException e) {
            Throwable cause = e.getCause();
            // 判断异常原因是否包含外键约束失败
            if (cause != null && cause.getMessage() != null && cause.getMessage().contains("a foreign key constraint fails")) {
                result.put("success", false);
                result.put("msg", "商品编号不存在，请先添加商品！");
                return result;
            }
            throw e;
        }
        return result;
    }

    // 根据detailId删除促销商品
    @DeleteMapping("/{detailId}")
    public boolean delete(@PathVariable Integer detailId) {
        return promotionProductService.removeById(detailId);
    }

    /**
     * 生成条形码并返回图片
     */

    @GetMapping("/{detailId}/barcode")
    public ResponseEntity<byte[]> generateBarcode(
            @PathVariable Integer detailId,
            @RequestParam(required = false) String barcode) throws UnsupportedEncodingException {

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 根据detailId查询活动商品信息
            PromotionProduct promotionProduct = promotionProductService.getById(detailId);
            if (promotionProduct == null) {
                // 返回JSON格式的错误信息，而不是字节数组
                String errorJson = "{\"error\":\"活动商品记录不存在\"}";
                return ResponseEntity.status(404)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(errorJson.getBytes("UTF-8"));
            }

            // 确定要使用的条形码内容
            String barcodeContent;
            if (barcode != null && !barcode.isEmpty()) {
                barcodeContent = barcode;
            } else if (promotionProduct.getBarcode() != null && !promotionProduct.getBarcode().isEmpty()) {
                barcodeContent = promotionProduct.getBarcode();
            } else {
                String errorJson = "{\"error\":\"条形码内容不能为空，请先设置条形码编号\"}";
                return ResponseEntity.status(400)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(errorJson.getBytes("UTF-8"));
            }

            // 生成条形码
            int width = 300;
            int height = 100;
            BitMatrix bitMatrix = new MultiFormatWriter().encode(
                    barcodeContent, BarcodeFormat.CODE_128, width, height);

            // 写入输出流
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);

            // 确保输出流完全写入
            outputStream.flush();

            // 获取字节数组
            byte[] imageBytes = outputStream.toByteArray();

            // 验证生成的图片数据是否有效
            if (imageBytes.length == 0) {
                String errorJson = "{\"error\":\"条形码生成失败，图片数据为空\"}";
                return ResponseEntity.status(500)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(errorJson.getBytes("UTF-8"));
            }

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setContentDispositionFormData("attachment", "barcode_" + barcodeContent + ".png");
            // 添加缓存控制
            headers.setCacheControl("no-cache");
            headers.setPragma("no-cache");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(imageBytes);

        } catch (com.google.zxing.WriterException e) {
            String errorJson = "{\"error\":\"无效的条形码格式: " + e.getMessage() + "\"}";
            return ResponseEntity.status(400)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(errorJson.getBytes("UTF-8"));
        } catch (Exception e) {
            String errorJson = "{\"error\":\"条形码生成失败: " + e.getMessage() + "\"}";
            return ResponseEntity.status(500)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(errorJson.getBytes("UTF-8"));
        }
    }

    /**
     * 根据商品编号或条形码查找所有活动，返回最低折扣价
     */
    @GetMapping("/best-price")
    public BigDecimal getBestPromotionPrice(@RequestParam(required = false) String productSerialNo,
                                            @RequestParam(required = false) String barcode) {
        return promotionProductService.getBestPromotionPrice(productSerialNo, barcode);
    }
}